package com.hckjsec.system.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import com.hckjsec.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hckjsec.common.annotation.Log;
import com.hckjsec.common.core.controller.BaseController;
import com.hckjsec.common.core.domain.AjaxResult;
import com.hckjsec.common.enums.BusinessType;
import com.hckjsec.system.domain.SysPostalcode;
import com.hckjsec.system.service.ISysPostalcodeService;
import com.hckjsec.common.utils.poi.ExcelUtil;
import com.hckjsec.common.core.page.TableDataInfo;

/**
 * 邮政编码Controller
 * 
 * @author cyt
 * @date 2021-09-23
 */
@RestController
@RequestMapping("/system/postalcode")
public class SysPostalcodeController extends BaseController
{
    @Autowired
    private ISysPostalcodeService sysPostalcodeService;

    /**
     * 获取邮政编码详细信息
     */
    @GetMapping(value = "/{code}")
    public AjaxResult getInfo(@PathVariable("code") String code) throws  Exception
    {
        System.out.println("开始抓取");
        Map<String,List<Map<String,String>>> maps = new LinkedHashMap<>();
        String url = "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2020/";
        maps = getprovinceinfo(url+"index.html","0", maps);
        //城市
        for(Map<String,String> map : maps.get("0")){
            getcityinfo(url+map.get("code")+".html",map.get("code"),"city",2,maps);
        }
        //区县
        Map<String,List<Map<String,String>>> maps1 = new LinkedHashMap<>();
        maps1.putAll(maps);
        for(Map.Entry<String, List<Map<String,String>>> m : maps1.entrySet()){
            for(Map<String,String> map : m.getValue()){
                if("2".equals(map.get("level"))){
                    getcityinfo(url+map.get("url")+".html",map.get("code"),"county",3,maps);
                }
            }
        }
        System.out.println("结束抓取");
        return null;
    }

    /**抓取区县信息*/
    public  Map<String,List<Map<String,String>>> getcountyinfo(String url, String parentCode, String key, Integer level, Integer len, Map<String,List<Map<String,String>>> maps) throws Exception{
        maps.put(parentCode, new ArrayList());
        try {
            String re = getURLinfo(url);
            //取省
            String sta1 = re.substring(re.indexOf(key+"table")+(key+"table").length());
            sta1 = sta1.substring(0, sta1.indexOf("</table>"));
            for(;;){
//            	System.out.println("sta1 = "+sta1);
                if(sta1.length()>0 && sta1.contains("<tr class='"+key+"tr'><td><a href='")
                        && sta1.contains("</a></td></tr>")
                        && sta1.contains(".html'>")){
                    String sta2 = sta1.substring(sta1.indexOf("<tr class='"+key+"tr'><td><a href='")+("<tr class='"+key+"tr'><td><a href='").length(), sta1.indexOf("</a></td></tr>"));
//					System.out.println("sta2 = "+sta2);

                    String[] s = sta2.split("</a></td><td><a href='");
//	            	System.out.println(s[0]+",,"+s[1]);
                    Map<String,String> map = new HashMap<String, String>();
                    map.put("parentCode", s[0].substring(0,s[0].indexOf("/")));
                    if(len!=null){
                        map.put("code", (s[0].substring(s[0].indexOf(">")+1).substring(0, len)));
                    }else{
                        map.put("code", (s[0].substring(s[0].indexOf(">")+1)));
                    }
                    map.put("name", s[1].substring(s[1].indexOf(">")+1));
                    map.put("url", s[0].substring(0,s[0].indexOf(".html")));
                    map.put("level","2");
                    maps.get(parentCode).add(map);
                    sta1 = sta1.substring(sta1.indexOf(sta2)+sta2.length()+"</a></td></tr>".length());
                }else{
                    break;
                }
            }
//			System.out.println(JsonUtil.obj2Json(maps));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return maps;
    }

    /**抓取城市信息*/
    public  Map<String,List<Map<String,String>>> getcityinfo(String url,String parentCode,String key,Integer level,Map<String,List<Map<String,String>>> maps) throws Exception{
        maps.put(parentCode, new ArrayList());
        try {
            String re = getURLinfo(url);
            //取省
            String sta1 = re.substring(re.indexOf(key+"table")+(key+"table").length());
            sta1 = sta1.substring(0, sta1.indexOf("</table>"));
            for(;;){
//            	System.out.println("sta1 = "+sta1);
                if(sta1.contains("<tr class='"+key+"tr'><td><a href='")
                        && sta1.contains("</a></td></tr>")
                        && sta1.contains(".html'>")){
                    String sta2 = sta1.substring(sta1.indexOf("<tr class='"+key+"tr'><td><a href='")+("<tr class='"+key+"tr'><td><a href='").length(), sta1.indexOf("</a></td></tr>"));
//					System.out.println("sta2 = "+sta2);

                    String[] s = sta2.split("</a></td><td><a href='");
//	            	System.out.println(s[0]+",,"+s[1]);
                    Map<String,String> map = new HashMap<String, String>();
                    map.put("parentCode", s[0].substring(0,s[0].indexOf("/")));
                    if(level!=null){
                        map.put("code", (s[0].substring(s[0].indexOf(">")+1).substring(0, level*2)));
                    }else{
                        map.put("code", (s[0].substring(s[0].indexOf(">")+1)));
                    }
                    map.put("name", s[1].substring(s[1].indexOf(">")+1));
                    if(level==2){
                        map.put("url", s[0].substring(0,s[0].indexOf(".html")));
                    }else if(level==3){
                        map.put("url",map.get("code").substring(0,2)+"/"+map.get("code").substring(2,4)+"/"+map.get("code"));
                    }
                    map.put("level",level+"");
                    maps.get(parentCode).add(map);
                    System.out.println("市：code======="+map.get("code")+"   name========"+map.get("name"));

                    String  code = map.get("code");
                    SysPostalcode sysPostalcode = new SysPostalcode();
                    sysPostalcode.setCode(code);
                    sysPostalcode.setCodeName(map.get("name"));
                    sysPostalcode.setCodeType(String.valueOf(level));
                    if (level == 2){
                        sysPostalcode.setProvinceCode(code.substring(0,2));
                    }else if (level == 3){
                        sysPostalcode.setProvinceCode(code.substring(0,2));
                        sysPostalcode.setCityCode(code.substring(0,4));
                    }
                    SysPostalcode postalcode = sysPostalcodeService.selectSysPostalcodeById(code);
                    if (StringUtils.isNull(postalcode)){
                        sysPostalcodeService.insertSysPostalcode(sysPostalcode);
                    }else{
                        sysPostalcodeService.updateSysPostalcode(sysPostalcode);
                    }

                    sta1 = sta1.substring(sta1.indexOf(sta2)+sta2.length()+"</a></td></tr>".length());
                }else{
                    break;
                }
            }
            // System.out.println(JSON.toJSONString(maps));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return maps;
    }
    /**抓取省份信息*/
    public  Map<String,List<Map<String,String>>> getprovinceinfo(String url,String parentCode,Map<String,List<Map<String,String>>> maps) throws Exception{
        maps.put(parentCode, new ArrayList());
        try {
            String re = getURLinfo(url);
            //取省
            String sta1 = re.substring(re.indexOf("provincetable")+"provincetable".length());
            sta1 = sta1.substring(0, sta1.indexOf("</table>"));
            for(;;){
//            	System.out.println("sta1 = "+sta1);
                if(sta1.contains("<td><a href='") && sta1.contains("<br/></a></td>")
                        && sta1.contains(".html'>")){
                    String sta2 = sta1.substring(sta1.indexOf("<td><a href='")+"<td><a href='".length(), sta1.indexOf("<br/></a></td>"));
//					System.out.println("sta2 = "+sta2);
                    String[] s = sta2.split("'>");
                    Map<String,String> map = new HashMap<String, String>();
                    map.put("code", s[0].substring(0, s[0].indexOf(".html")));
                    map.put("name", s[1]);
                    System.out.println("省：code======="+map.get("code")+"   name========"+map.get("name"));
                    map.put("level", "1");
                    maps.get("0").add(map);


                    String  code = map.get("code");
                    SysPostalcode sysPostalcode = new SysPostalcode();
                    sysPostalcode.setCode(code);
                    sysPostalcode.setCodeName(map.get("name"));
                    sysPostalcode.setCodeType("1");
                    SysPostalcode postalcode = sysPostalcodeService.selectSysPostalcodeById(code);
                    if (StringUtils.isNull(postalcode)){
                        sysPostalcodeService.insertSysPostalcode(sysPostalcode);
                    }else{
                        sysPostalcodeService.updateSysPostalcode(sysPostalcode);
                    }
                    sta1 = sta1.substring(sta1.indexOf(sta2)+sta2.length()+"<br/></a></td>".length());
                }else{
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return maps;
    }
    public static String getURLinfo(String urlstr) throws Exception{
        StringBuilder result = new StringBuilder();
        URL url = new URL(urlstr);
        //通过URL的openStrean方法获取URL对象所表示的自愿字节输入流
        // InputStream is = url.openStream();
        HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
        htpcon.setRequestMethod("GET");htpcon.setDoOutput(true);
        htpcon.setDoInput(true);
        htpcon.setUseCaches(false);
        htpcon.setConnectTimeout(1000);
        htpcon.setReadTimeout(1000);
        InputStream is = url.openStream();
        InputStreamReader isr = new InputStreamReader(is,"gb2312");
        //为字符输入流添加缓冲
        BufferedReader br = new BufferedReader(isr);
        String data = br.readLine();//读取数据

        while (data!=null){//循环读取数据
//            System.out.println(data);//输出数据
            result.append(data);
            data = br.readLine();
        }
        br.close();
        isr.close();
        is.close();
        return result.toString();
    }
}
